package edu.cs.networkmonitor.devices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.Date;

public class IPSource extends BaseSource {
 
	public String _ipAddress;

	public IPSource(String address) {
		_ipAddress = address;
		_sourceName = address;
	}
	
	public boolean connectOld() {
		System.out.println("Trying to connect to " + _sourceName + new Date().toString());
		boolean status = false;
		try {
			return InetAddress.getByName(_ipAddress).isReachable(1000);
		} catch (Exception e) {
			e.printStackTrace();
			status = false;
		} 
		_lastStatus = status;
		return status;
	}
	@Override
	public boolean connect() {
		boolean status = false;
		try {
			Process p = Runtime.getRuntime().exec("ping " + _ipAddress +" -n 1");
			BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
			StringBuilder builder = new StringBuilder();
			String s;
			while ((s = stdInput.readLine()) != null) {
				builder.append(s);
				System.out.println(s);
			}
			p.destroy();
			if (p.exitValue() != 0 || builder.toString().contains("unreachable") || builder.toString().contains("fail") || builder.toString().contains("error")) {
				System.out.println(_ipAddress + " unreachable");
				status = false;
			} else {
				System.out.println(_ipAddress + " reachable");
				status = true;
			}
		} catch (IOException e) {
			e.printStackTrace();
			status = false;
		}
		_lastStatus = status;
		return status;
	}

	@Override
	public String getEmailSubject() {
		return "IP connection lost" + new Date().toString(); 
	}

	@Override
	public String getEmailBody() {
		return "Cannot connect to : \n\t\t" + _ipAddress + " [" +  _sourceDescription + "] " + "\n Time: "+ new Date().toString();

	}
}
